/**
 * 资料详情页
 */
package com.xiaomuwu.android.ui.detail

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.xiaomuwu.android.MainActivity
import com.xiaomuwu.android.R
import com.xiaomuwu.android.XiaoMuWuApplication
import com.xiaomuwu.android.logic.Repository
import com.xiaomuwu.android.logic.model.ForDownLoad
import com.xiaomuwu.android.logic.model.ForLike
import com.xiaomuwu.android.logic.model.ForResDetail
import com.xiaomuwu.android.ui.Displayer
import com.xiaomuwu.android.ui.ForSearch
import com.xiaomuwu.android.ui.LoginStatus
import com.xiaomuwu.android.ui.upload.UploadResFragment
import com.xiaomuwu.android.ui.webpage.WebpageFragment
import kotlinx.android.synthetic.main.res_detail_fragment.*

class ResDetailFragment:Fragment() {

    private val viewModel by lazy{ ViewModelProviders.of(this).get(
        ResDetailViewModel::class.java)}

    private var isPraised=false // 是否已点赞

    private var isCollected=false   // 是否已收藏

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.res_detail_fragment,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if(Displayer.prevPageStatus == "Upload" || Displayer.pprevPageStatus == "ModifyRes") {
            // 显示 “修改” 和 “取消分享” 按钮
            modifyRes?.visibility = View.VISIBLE
            delete?.visibility = View.VISIBLE
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel.resDetailLiveData.observe(viewLifecycleOwner, { result->
            resDetailName.text = Displayer.resName  // 显示资料名
            val resDetail=result.getOrNull()
            if(resDetail!=null){
                resUploader.text="由 ${resDetail.uploader} 上传"   // 显示上传者
                resAbout.text=resDetail.about   // 显示资料简介
                isPraised = if(resDetail.isPraised==1){
                    imagePraise.setImageResource(R.drawable.praised)    // 设置 “已点赞” 图标
                    true
                }else{
                    imagePraise.setImageResource(R.drawable.praise) // 设置 “未点赞” 图标
                    false
                }
                isCollected=if(resDetail.isCollected==1){
                    imageCollect.setImageResource(R.drawable.collected) // 设置 “已收藏” 图标
                    true
                }else{
                    imageCollect.setImageResource(R.drawable.collect)   // 设置 “未收藏” 图标
                    false
                }
                countPraiseText.text=resDetail.praiseCount.toString()   // 显示点赞数
                countDownloadText.text=resDetail.downloadCount.toString()   // 显示下载数
                countCollectText.text=resDetail.collectCount.toString() // 显示收藏数

                // 更新资料信息
                Displayer.praiseCount=resDetail.praiseCount
                Displayer.downloadCount=resDetail.downloadCount
                Displayer.collectCount=resDetail.collectCount
                Displayer.resLink=resDetail.resLink
                Displayer.resAbout=resDetail.about

                Log.d("ResDetailFragment","ResDetail查询成功")
            }else{
                Log.d("ResDetailFragment","ResDetail查询失败")
            }
        })
        viewModel.getResDetailLiveData(ForResDetail(LoginStatus.user_ID,ForSearch.resID))

        // 点赞、收藏操作：先更新UI上的数字，待退出资料详情页后再操作数据库
        // “点赞” 图标点击监听
        imagePraise?.setOnClickListener {
            if(LoginStatus.user_ID==null){
                Toast.makeText(XiaoMuWuApplication.context,"请先登录",
                    Toast.LENGTH_SHORT).show()
            }else{
//                if(isPraised){
//                    Repository.praiseRes(ForLike(LoginStatus.user_ID,ForSearch.resID,"delete"))
//                    Log.d("ResDetailFragment","delete praise 成功")
//                }else{
//                    Repository.praiseRes(ForLike(LoginStatus.user_ID,ForSearch.resID,"insert"))
//                    Log.d("ResDetailFragment","insert praise 成功")
//                }
                isPraised = if(isPraised){
                    imagePraise.setImageResource(R.drawable.praise) // 设置 “未点赞” 图标

                    // 更新UI点赞数
                    Displayer.praiseCount--
                    countPraiseText.text=Displayer.praiseCount.toString()

                    ForSearch.praiseCountChange--   // 更新点赞数变化
                    false
                }else{
                    imagePraise.setImageResource(R.drawable.praised)    // 设置 “已点赞” 图标

                    // 更新UI点赞数
                    Displayer.praiseCount++
                    countPraiseText.text=Displayer.praiseCount.toString()

                    ForSearch.praiseCountChange++   // 更新点赞数变化
                    true
                }
            }
//            viewModel.getResDetailLiveData(ForResDetail(LoginStatus.user_ID,ForSearch.resID))
        }

        // “收藏” 图标点击监听
        imageCollect?.setOnClickListener {
            if(LoginStatus.user_ID==null){
                Toast.makeText(XiaoMuWuApplication.context,"请先登录",
                    Toast.LENGTH_SHORT).show()
            }else{
//                if(isCollected){
//                    Repository.collectRes(ForLike(LoginStatus.user_ID,ForSearch.resID,"delete"))
//                }else{
//                    Repository.collectRes(ForLike(LoginStatus.user_ID,ForSearch.resID,"insert"))
//                }
                isCollected=if(isCollected){
                    imageCollect.setImageResource(R.drawable.collect)   // 设置 “未收藏” 图标

                    // 更新UI收藏数
                    Displayer.collectCount--
                    countCollectText.text=Displayer.collectCount.toString()

                    ForSearch.collectCountChange--  // 更新收藏数变化
                    false
                }else{
                    imageCollect.setImageResource(R.drawable.collected) // 设置 “已收藏” 图标

                    // 更新UI收藏数
                    Displayer.collectCount++
                    countCollectText.text=Displayer.collectCount.toString()

                    ForSearch.collectCountChange++  // 更新收藏数变化
                    true
                }
            }
//            viewModel.getResDetailLiveData(ForResDetail(LoginStatus.user_ID,ForSearch.resID))
        }

        // “下载” 图标点击监听
        imageDownload.setOnClickListener {
            if(LoginStatus.user_ID==null){
                Toast.makeText(
                    XiaoMuWuApplication.context,"请先登录", Toast.LENGTH_SHORT
                ).show()
            }else{
                // 切换至资料链接页并下载
                if(activity!=null) {
                    val mainActivity=activity as MainActivity
                    Displayer.pprevPageStatus=Displayer.prevPageStatus
                    Displayer.prevPageStatus=Displayer.pageStatus
                    Displayer.pageStatus="WebPage"
                    mainActivity.replaceFragment(WebpageFragment())

                    // 下载
                    Repository.downloadRes(ForDownLoad(LoginStatus.user_ID!!,ForSearch.resID))
                }
            }
        }

        // “修改” 按钮点击监听
        modifyRes?.setOnClickListener {
            // 切换至上传（修改）页
            if(activity!=null){
                val mainActivity=activity as MainActivity
                Displayer.pprevPageStatus=Displayer.prevPageStatus
                Displayer.prevPageStatus=Displayer.pageStatus
                Displayer.pageStatus="ModifyRes"
                mainActivity.replaceFragment(UploadResFragment())
            }
        }

        // “取消分享” 按钮点击监听
        delete?.setOnClickListener {
            Repository.deleteRes(ForSearch.resID)   // 取消分享

            // 返回
            if(activity!=null){
                val mainActivity=activity as MainActivity
                mainActivity.onBackPressed()
            }
        }
    }

    override fun onPause() {
        super.onPause()

        // 执行资料详情页的操作
        if (ForSearch.praiseCountChange == 1) {
            // 点赞
            Repository.likeRes(
                ForLike(
                    LoginStatus.user_ID!!,ForSearch.resID, "praise",
                    "insert"
                )
            )
        } else if (ForSearch.praiseCountChange == -1) {
            // 取消点赞
            Repository.likeRes(
                ForLike(
                    LoginStatus.user_ID!!,ForSearch.resID, "praise",
                    "delete"
                )
            )
        }
        if (ForSearch.collectCountChange == 1) {
            // 收藏
            Repository.likeRes(
                ForLike(
                    LoginStatus.user_ID!!,ForSearch.resID, "collect",
                    "insert"
                )
            )
        } else if (ForSearch.collectCountChange == -1) {
            // 取消收藏
            Repository.likeRes(
                ForLike(
                    LoginStatus.user_ID!!,ForSearch.resID, "collect",
                    "delete"
                )
            )
        }
        ForSearch.praiseCountChange=0   // 重置点赞数变化
        ForSearch.collectCountChange=0  // 重置收藏数变化
    }

}